package yzy.test.web.handler;

import yzy.test.mvc.Controller;
import yzy.test.mvc.RequestMapping;
import yzy.test.mvc.RequestParam;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

public class HandlerManager {
    public static List<MappingHandler> mappingHandlerList = new ArrayList<>();

    public static void resovleMappingHandler(List<Class<?>> classList){
        for(Class<?> clazz : classList){
            if(clazz.isAnnotationPresent(Controller.class)){
                parseHandler(clazz);
            }
        }
    }

    /**
     * 通过注解,解析Controller的元信息
     * @param clazz
     */
    private static void parseHandler(Class<?> clazz) {
        Method[] methods = clazz.getDeclaredMethods();
        for(Method method : methods){
            if(!method.isAnnotationPresent(RequestMapping.class)){
                continue;
            }
            String uri = method.getDeclaredAnnotation(RequestMapping.class).value();
            List<String> paramNameList = new ArrayList<>();
            for(Parameter parameter : method.getParameters()){
                if(parameter.isAnnotationPresent(RequestParam.class)){
                    paramNameList.add(parameter.getDeclaredAnnotation(RequestParam.class).value());
                }
            }
            String[] params =  paramNameList.toArray(new String[paramNameList.size()]);
            MappingHandler handler = new MappingHandler(uri, clazz, method, params);
            mappingHandlerList.add(handler);
        }
    }
}
